package jt.classic.app.dms.scanner;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jt.classic.app.dms.DmsManager;
import jt.classic.system.AbstractSimpleManager;
import jt.classic.system.ISystem;
import jt.classic.system.ISystemException;
import jt.classic.system.object.IObject;
import jt.classic.system.object.ObjectManager;
import jt.classic.system.user.IUser;

import org.limp.basework.Table;
import org.limp.basework.impl.CommonBean4HSQ;
import org.limp.mine.annex.AnnexItem;
import org.limp.mine.annex.AnnexItemImpl;
import org.limp.mine.annex.AttDiscFileItemImpl;
import org.limp.mine.annex.AttFileItem;


/**
 * FTP文档扫描器
 *
 * @author mido
 *
 */
public class DMSFtpFileScanner extends AbstractSimpleManager {
    public DMSFtpFileScanner(Connection conn) {
        super(conn);
    }

    /**
     * 扫描ftp文件夹
     *
     * @param folder
     *            文件夹
     * @param user
     *            文件夹所属用户
     */
    public void scanFtpFolder(File folder, IUser user)
        throws ISystemException {
        File ftpfolder = new File(folder, "uploads");

        File[] files = ftpfolder.listFiles(new FtpFileFilter());

        if ((files != null) && (files.length > 0)) {
            for (int i = 0; i < files.length; i++) {
                DMSFtpFileChecker checker = new DMSFtpFileChecker();

                try {
                    if (checker.checkFtpFile(files[i], files[i].lastModified(),
                                500)) {
                        DMSFtpFileArray dffa = DMSFtpFileArray.getInstance();

                        if (!dffa.contansFile(files[i], user)) {
                            dffa.push(files[i], user);
                        }
                    }
                } catch (Exception ex) {
                    throw new ISystemException(ex);
                }
            }
        }
    }

    /**
     * 将ftp上传文件增加到DMS
     * @param file 上传文件
     * @param user 文件所属用户
     * @throws ISystemException
     */
    public void autoSave(File file, IUser user) throws ISystemException {
        CommonBean4HSQ cbh = null;

        try {
            cbh = new CommonBean4HSQ(null);
        } catch (Exception ex) {
            ISystem.catchException(ex);
        }

        int size = getFileSize(file);

        cbh.getResource().put("COL_FILENAME", file.getName());
        cbh.getResource().put("oname", file.getName());

        String originalFilename = file.getName();
        String fileType = (originalFilename.lastIndexOf(".") > -1)
            ? originalFilename.substring(originalFilename.lastIndexOf(".") + 1)
            : "";
        cbh.getResource().put("COL_FILETYPE", fileType);

        /* 设置其它内容 */
        cbh.getResource().put("COL_DIRECTORYID", DmsManager.DEFAULT_FOLDER_ID);
        cbh.getResource().put("COL_FILESIZE", String.valueOf((size / 1024)));
        cbh.getResource().put("COL_STATE", "00");
        cbh.getResource().put("COL_VERSION", "1.0");

        cbh.getResource().put("okey", "FILEINFO");

        cbh.getResource().put("ocreatorid", user.id());
        cbh.getResource().put("ocreatorname", user.iname());
        cbh.getResource()
           .put("ounitid", (user.igroup() != null) ? user.igroup().id() : "-1");
        cbh.getResource()
           .put("ounitname",
            (user.igroup() != null) ? user.igroup().iname() : "");
        cbh.getResource()
           .put("ounitnumber",
            (user.igroup() != null) ? user.igroup().iname() : "");

        /* 获取上传文件 */
        AttFileItem afitem = new AttDiscFileItemImpl(file, "UTF-8");

        /* 上传文件Map */
        Map annexInfo = new HashMap();
        annexInfo.put("file1", afitem); // 其中fieldName为文件表单数据实体对应的formname。
                                        /* 待处理附件实例 */

        AnnexItem annexitem = new AnnexItemImpl(annexInfo);

        /* 设置文件实体内容 */
        cbh.getResource().put(AnnexItem.ANNEX, annexitem);

        ObjectManager om = new ObjectManager(this.conn);

        IObject obj = om.auto("FILEINFO", cbh);

        Table table = obj.iobject().itable("DOC_BVFABRYJMQ");
        Map result = ((Map) ((List) obj.icontent(table)).get(0));
        String fileId = (String) result.get("PK_DOC_BVFABRYJMQ");

        DmsManager dm = new DmsManager(this.conn);

        dm.insertEvent(fileId, user.id(), user.iname(), "创建了文档(FTP上传)",
            "FILEINFO", "1.0");

        file.delete();
    }

    /**
     * 文件大小
     * @param file 文件实例
     * @return int
     */
    private int getFileSize(File file) {
        int size = 0;

        try {
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(
                        file));
            size = fis.available();
            fis.close();
        } catch (Exception ex) {
            ISystem.catchException(ex);
        }

        return size;
    }

    /**
     * ftp上传文件过滤器
     *
     * @author mido
     *
     */
    private class FtpFileFilter implements FileFilter {
        /**
         *
         * 过滤有效的文件
         *
         * @param file
         * @return boolean
         *
         */
        public boolean accept(File file) {
            if (file.isFile()) {
                String fileName = file.getName();

                String expandName = ((fileName.lastIndexOf(".") > -1) &&
                    (fileName.lastIndexOf(".") < fileName.length()))
                    ? fileName.substring(fileName.lastIndexOf(".") + 1) : "";

                return true;
            }

            return false;
        }
    }

    /**
     * 不是ftp上传文件过滤器
     *
     * @author mido
     *
     */
    private class NotFtpFileFilter implements FileFilter {
        /**
         *
         * 过滤有效的文件
         *
         * @param file
         * @return boolean
         *
         */
        public boolean accept(File file) {
            if (file.isFile()) {
                String fileName = file.getName();

                String expandName = ((fileName.lastIndexOf(".") > -1) &&
                    (fileName.lastIndexOf(".") < fileName.length()))
                    ? fileName.substring(fileName.lastIndexOf(".") + 1) : "";

                return !expandName.equals("dff");
            }

            return false;
        }
    }
}
